<?php

namespace App\Services;

use App\Models\Cart;
use App\Models\CartItem;
use App\Models\Product;
use App\Models\ProductVariant;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

class CartService
{
    /**
     * 获取或创建购物车
     */
    public function getOrCreateCart($userId = null, $sessionId = null): Cart
    {
        return Cart::getOrCreate($userId, $sessionId);
    }

    /**
     * 合并游客购物车到用户购物车
     */
    public function mergeGuestCartToUser($userId, $sessionId): void
    {
        DB::transaction(function () use ($userId, $sessionId) {
            // 获取游客购物车
            $guestCart = Cart::where('session_id', $sessionId)->first();
            
            if (!$guestCart || $guestCart->items->isEmpty()) {
                return;
            }

            // 获取用户购物车
            $userCart = Cart::getOrCreate($userId, null);

            // 合并购物车商品
            foreach ($guestCart->items as $guestItem) {
                $existingItem = $userCart->items()
                    ->where('product_id', $guestItem->product_id)
                    ->where('variant_id', $guestItem->variant_id)
                    ->first();

                if ($existingItem) {
                    // 合并数量
                    $newQuantity = $existingItem->quantity + $guestItem->quantity;
                    
                    // 检查库存
                    $stock = $this->getProductStock($guestItem->product_id, $guestItem->variant_id);
                    $newQuantity = min($newQuantity, $stock);
                    
                    $existingItem->update(['quantity' => $newQuantity]);
                } else {
                    // 创建新商品项
                    $guestItem->update(['cart_id' => $userCart->id]);
                }
            }

            // 删除游客购物车
            $guestCart->delete();
        });
    }

    /**
     * 从session购物车迁移到数据库购物车
     */
    public function migrateSessionCartToDatabase($userId = null, $sessionId = null): void
    {
        $sessionCart = Session::get('cart', []);
        
        if (empty($sessionCart)) {
            return;
        }

        DB::transaction(function () use ($sessionCart, $userId, $sessionId) {
            $cart = $this->getOrCreateCart($userId, $sessionId);

            foreach ($sessionCart as $key => $item) {
                $product = Product::find($item['product_id']);
                $variant = $item['variant_id'] ? ProductVariant::find($item['variant_id']) : null;

                if (!$product) {
                    continue;
                }

                // 检查是否已存在
                $existingItem = $cart->items()
                    ->where('product_id', $product->id)
                    ->where('variant_id', $variant?->id)
                    ->first();

                if ($existingItem) {
                    // 更新数量
                    $newQuantity = $existingItem->quantity + $item['quantity'];
                    $stock = $this->getProductStock($product->id, $variant?->id);
                    $newQuantity = min($newQuantity, $stock);
                    
                    $existingItem->update(['quantity' => $newQuantity]);
                } else {
                    // 创建新商品项
                    $price = $variant ? $variant->price : $product->price;
                    
                    // 根据商品类型处理规格信息
                    if ($product->product_type === 'single') {
                        // 单规格商品，不设置规格信息
                        $specifications = null;
                    } else {
                        // 多规格商品，从变体获取规格信息
                        $specifications = $variant ? $this->getVariantSpecifications($variant) : null;
                    }
                    
                    $image = $this->getProductImage($product, $variant);

                    CartItem::create([
                        'cart_id' => $cart->id,
                        'product_id' => $product->id,
                        'variant_id' => $variant?->id,
                        'quantity' => $item['quantity'],
                        'price' => $price,
                        'specifications' => $specifications,
                        'image' => $image,
                    ]);
                }
            }

            // 清空session购物车
            Session::forget('cart');
        });
    }

    /**
     * 获取商品库存
     */
    private function getProductStock($productId, $variantId = null): int
    {
        if ($variantId) {
            $variant = ProductVariant::find($variantId);
            return $variant ? $variant->stock_quantity : 0;
        }

        $product = Product::find($productId);
        return $product ? $product->stock_quantity : 0;
    }

    /**
     * 获取变体规格信息
     */
    private function getVariantSpecifications(ProductVariant $variant): array
    {
        return $variant->attributeValues()
            ->with('attribute')
            ->get()
            ->map(function ($value) {
                return [
                    'name' => $value->attribute->name,
                    'value' => $value->display_value,
                ];
            })
            ->toArray();
    }

    /**
     * 获取商品图片
     */
    private function getProductImage(Product $product, ?ProductVariant $variant): ?string
    {
        if ($variant && $variant->images->isNotEmpty()) {
            return $variant->images->first()->image_path;
        }
        
        if ($product->images->isNotEmpty()) {
            return $product->images->first()->image_path;
        }
        
        return null;
    }
}
